<template>
  <div>
    <a-modal
      ok-text="确认"
      cancel-text="取消"
      :maskClosable="false"
      :title="title + '工序'"
      :width="modalWidth"
      @cancel="handleClose"
      :visible="visible"
      :destroyOnClose="true"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      footer=""
    >
      <template>
        <div class="modalBut">
          <a-button @click="handleClose">
            取消
          </a-button>
          <a-button @click="handleOk" type="primary">确认</a-button>
        </div>
      </template>
      <div
        :style="{
          width: '100%',
          border: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
        }"
      >
        <a-spin :spinning="confirmLoading">
          <a-form-model ref="ruleForm" :model="model" :rules="rules">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="工序序号"
              prop="workStageId"
              hasFeedback
            >
              <a-input
                placeholder="请输入工序序号"
                v-model.trim="model.workStageId"
              >
                <a-tooltip slot="suffix" title="请输入整数,比如:10,20,30">
                  <a-icon
                    type="question-circle"
                    style="color: rgba(24, 144, 255)"
                  />
                </a-tooltip>
              </a-input>
            </a-form-model-item>

            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="工序名称"
              hasFeedback
              prop="workStageName"
            >
              <a-input
                placeholder="请输入工序名称"
                v-model.trim="model.workStageName"
              />
            </a-form-model-item>

            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="工序内容"
              hasFeedback
              prop="workStageContent"
            >
              <a-input
                placeholder="请输入工序内容"
                v-model.trim="model.workStageContent"
              />
            </a-form-model-item>

            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="工序单价"
              hasFeedback
              prop="referencePrice"
            >
              <a-input
                placeholder="请输入工序单价"
                v-model.trim="model.referencePrice"
              />
            </a-form-model-item>

            <div
              class="flex flex-a-c equipBox"
              v-for="(item, index) in model.equipIdAndCapacityMap"
              :key="index"
            >
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                :label="`设备${index + 1}`"
                hasFeedback
                :rules="rules.equipId"
                :prop="`equipIdAndCapacityMap[${index}].equipId`"
              >
                <a-select
                  style="width:175px"
                  :open="false"
                  :defaultOpen="false"
                  mode="multiple"
                  :allowClear="true"
                  placeholder="选择设备"
                  v-model.trim="item.equipId"
                  @dropdownVisibleChange="
                    (open) => handleTableSelect(open, index)
                  "
                  @change="handleChange"
                >
                  <a-select-option
                    v-for="item in tableOption"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.equipmentNumber }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>

              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="产能"
                hasFeedback
                :rules="rules.capacity"
                :prop="`equipIdAndCapacityMap[${index}].capacity`"
              >
                <a-input
                  type="number"
                  style="width:175px"
                  placeholder="请输入产能"
                  v-model.trim="item.capacity"
                />
              </a-form-model-item>
              <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-icon
                  v-if="model.equipIdAndCapacityMap.length - 1 === index"
                  type="plus-circle"
                  class="iconBox"
                  @click="handleCapacityAdd"
                ></a-icon>
                <a-icon
                  v-else
                  type="close"
                  class="iconBox"
                  @click="handleCapacityDelete(index)"
                />
              </a-form-model-item>
            </div>

            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="备注"
              hasFeedback
              prop="note"
            >
              <a-input placeholder="请输入备注" v-model.trim="model.note" />
            </a-form-model-item>
          </a-form-model>
        </a-spin>
      </div>
    </a-modal>

    <TableSelectModal
      :columns="columns"
      :replaceFields="replaceFields"
      :treeKey="treeKey"
      :searchKey="searchKey"
      :tableKey="tableKey"
      :name="name"
      :code="code"
      :filename="filename"
      ref="tableModal"
      :mode="mode"
      @tableSelect="tableSelect"
    ></TableSelectModal>
  </div>
</template>

<script>
import api from "@/api/apiServer";
import TableSelectModal from "@/components/TableSelectModal";
import { isNum } from "../../../unit/rule";
import { columns } from "./components/tableConfig";

export default {
  components: { TableSelectModal },
  data() {
    return {
      title: "", // 标题
      visible: false, // 状态、
      modalWidth: 700, // 抽屉宽度
      model: {
        equipIdAndCapacityMap: [{ equipId: undefined, capacity: "" }],
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      rules: {
        workStageId: [
          { required: true, message: "请输入工序序号", trigger: "change" },
          { validator: this.checkData, trigger: "change" },
        ],
        workStageName: [
          { required: true, message: "请输入工序名称", trigger: "change" },
        ],
        referencePrice: [{ validator: isNum, trigger: "change" }],
        // referencePrice: [{ required: true, message: "请输入工序单价" }],
        equipId: [
          {
            required: true,
            message: "请输入选择机台",
            trigger: "change",
          },
        ],
        capacity: [
          { required: true, message: "请输入产能", trigger: "change" },
        ],
        // note: [{ required: true, message: "请输入备注" }],
      },
      Option: [],
      list: [],
      // 选中组件参数
      replaceFields: {
        children: "equipmentTypeList",
        title: "equipmentTypeName",
        key: "id",
      },
      treeKey: "equipmentTypeList",
      tableKey: "equipmentListPage",
      searchKey: "equipmentType",
      name: "equipmentName",
      code: "equipmentNumber",
      mode: "radio",
      filename: "EquipMentModal",
      columns: columns,
      tableOption: [],
      current: 0, // 当前选择的设备
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    handleCapacityAdd() {
      this.model.equipIdAndCapacityMap = [
        ...this.model.equipIdAndCapacityMap,
        { equipId: undefined, capacity: "" },
      ];
    },
    checkData(rule, value, callback) {
      if (value) {
        if (/[\u4E00-\u9FA5]/g.test(value)) {
          callback(new Error("工序序号不能包含中文!"));
        } else {
          callback();
        }
      }
      callback();
    },
    // 表单删除
    handleCapacityDelete(index) {
      if (this.model.equipIdAndCapacityMap.length === 1) {
        return;
      }
      this.model.equipIdAndCapacityMap = this.model.equipIdAndCapacityMap.filter(
        (item, i) => i != index
      );
    },
    // 新增
    modalAdd() {
      this.modalEdit(this.model);
    },
    handleTableSelect(open, index) {
      this.current = index;
      this.$refs.tableModal.title = "设备";
      this.$refs.tableModal.modalAdd();
      if (this.model.equipIdAndCapacityMap.length > 0) {
        this.$refs.tableModal.selectedRowKeys = [
          this.model.equipIdAndCapacityMap[this.current].equipId,
        ];
      }
    },
    handleChange(value) {
      this.model.equipIdAndCapacityMap[this.current].equipId = value;
      this.$refs.ruleForm.clearValidate(["`equipIdAndCapacityMap[0].equipId`"]);
    },
    // 编辑
    modalEdit(record) {
      this.resetScreenSize();
      this.visible = true;
      this.model = Object.assign({}, record);
      if (this.model.equipIdAndCapacityMap === null) {
        this.model.equipIdAndCapacityMap = [
          { equipId: undefined, capacity: "" },
        ];
      }
    },
    // 关闭
    handleClose() {
      this.visible = false;
      this.model = Object.assign({});
      this.model.equipIdAndCapacityMap = [{ equipId: undefined, capacity: "" }];
      this.$refs.ruleForm.resetFields();
    },

    handleOk() {
      const that = this;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          that.handleSubmit();
          that.model = Object.assign({});
          that.model.equipIdAndCapacityMap = [
            { equipId: undefined, capacity: "" },
          ];
        } else {
          return false;
        }
      });
    },

    async handleSubmit() {
      this.confirmLoading = false;
      this.visible = false;
      let { equipIdAndCapacityMap } = this.model;
      let equipNums = [];
      let totalCapacity = 0;
      equipIdAndCapacityMap.forEach((item) => {
        totalCapacity += Number(item.capacity);
        this.tableOption.forEach((element) => {
          if (item.equipId == element.id) {
            equipNums.push(element.equipmentNumber);
          }
        });
      });
      this.model.equipNums = equipNums.toString();
      this.$emit("setData", this.model, totalCapacity, this.title);
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.modalWidth = screenWidth;
      } else {
        this.modalWidth = 700;
      }
    },
    async getList() {
      const res = await api.equipmentList();
      this.list = res.data;
    },
    tableSelect(result, tableOption) {
      this.tableOption = tableOption;
      this.model.equipIdAndCapacityMap[this.current].equipId = result[0].id;
      this.$refs.ruleForm.clearValidate(
        `equipIdAndCapacityMap[${this.current}].equipId`
      );
    },
  },
};
</script>

<style scoped lang="less">
.equipBox {
  margin-left: 94px;
  .iconBox {
    margin-left: 20px;
  }
}
</style>
